<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <searchrevealing>
                <el-tabs v-model="activeTab">
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="104px">
                        <el-form-item label="招商员姓名" prop="content">
                            <el-input v-model="queryParams.userName" placeholder="请输入" clearable style="width: 220px"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="招商员花名" prop="content">
                            <el-input v-model="queryParams.stageName" placeholder="请输入" clearable style="width: 220px"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="部门名称" prop="recruiterDeptIds">
                            <el-select v-model="queryParams.deptId" placeholder="请选择部门名称" clearable filterable
                                @change="deptChange" style="width: 220px">
                                <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="时间" prop="recruiterDeptIds">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="queryParams.time" type="daterange"
                                @change="pickerChange" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                                style="width: 220px" />
                        </el-form-item>
                    </el-form>
                    <div class="form_button">
                        <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
                        <el-button @click="resetQuery" :loading="loading">重置</el-button>
                    </div>
                </el-tabs>
            </searchrevealing>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain @click="handleOperate()">排行榜</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'排行榜数据管理'"
                        @updateColumn="getColmun"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" :data="tableData" border @header-dragend="dragEnd">
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <el-table-column v-for="(item, index) in commodityManage" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" >
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <div v-if="item.prop == 'hmMechanismsList'">
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[0] ||
                                null,
                                '一') }}
                            </div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[1] ||
                                null,
                                '二') }}
                            </div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[2] ||
                                null,
                                '三') }}
                            </div>
                        </div>
                        <div v-if="item.prop == 'supplierName'">
                            <div class="supplierName">
                                <img :src="visaExemption" class="visaExemption" v-if="scope.row.bigBrandStatus == 1" />
                                <div class="supplierName_text">{{ scope.row.supplierName }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right">
                    <template #default="scope">
                        <el-button link size="small" type="primary"
                            @click="handleInfo(scope.row, '招商排行榜数据维护')">操作</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableTotal > 0" :total="tableTotal" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" :page-sizes="[10]" />
        </el-card>

        <el-drawer v-model="isAddDrawer" :title="AddFormTitle" direction="rtl" size="70%" :before-close="handleClose"
            :close-on-click-modal="false">
            <AddForm v-if="isAddDrawer" @onSubmit="AddFormSubmit" :title="AddFormTitle" :AddFormId="AddFormId"
                :disabledName="disabledName" :AddFormlist='AddFormlist' />
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance() as any;
import { hmProductsPcList } from '@/api/group/productOutbound/index'
import { categoryList } from '@/api/system/supplierAddProducts';
import { type Action } from 'element-plus'
import { auditStatusNameById, handleEditPermission } from '@/utils/auditStatusFilter'
import { loginSupplierByRoleList } from '@/api/group/supplier/index'
import visaExemption from '@/assets/images/visaExemption.png'
import { removeInvalidNodes } from '@/utils/index'
import Qs from "qs";
import { getUserList, loginDeptList, getSystemList } from '@/api/group/qualityControl'
import AddForm from './addform/index.vue'
import { listColumn } from '@/api/system/column';
import { editFive, editOff, editTen, outSupplier } from '@/api/group/product/index'
import { getAnchorList } from '@/api/group/productSelectionPricing'
import {
    hmRankinglist
} from '@/api/group/list/index'

// 周 change事件
const zhou = () => {
    console.log(queryParams.value.recruiterDeptIds)
}







const commodityManage = ref()
const columnData = ref()
const statusList = ref([
    {
        label: "未邮寄",
        value: "0",
    },
    {
        label: "待收货",
        value: "2",
    },
    {
        label: "待上架",
        value: "4",
    },
    {
        label: "待选品",
        value: "5",
    },
    {
        label: "已选品",
        value: "6",
    },
    {
        label: "待入库",
        value: "15",
    },
    {
        label: "入库中",
        value: "16",
    },
    {
        label: "已入库",
        value: "18",
    },

]);
const activeTab = ref('qualityControl');
const queryFormRef = ref();
const isAddDrawer = ref(false)
const showSearch = ref(true);
const loading = ref(false);
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    deptId: '',
    userName: '',
    stageName: '',
    startTime: '',
    endTime: '',

})
const ids = ref<Array<any>>([]);
// 选中商品状态
const selectedStatus = ref<Array<any>>([])
const tableData = ref([])
const tableTotal = ref(0)
const categoryProps = ref([])
const supplierNameOptions = ref<any[]>([])
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const AddFormTitle = ref('')
const AddFormId = ref('')
const disabledName = ref('')
const supplierLoading = ref(true)
const supplierNameDate = ref<any>({
    pageNum: 1,
    pageSize: 10,
    supplierName: ''
})
const supplierQueryLoading = ref(false)
const supplierNametotal = ref()
const anchorList = ref<{ remark: string; userId: string }[]>([]);
// 时间
const startTime = ref()
// 核价通过时间
const pricingTime = ref()
// 选品时间
const selectionTime = ref()
// 合同状态
const contractList = ref([
    { label: '已上传', value: '1' },
    { label: '未上传', value: '0' },
    { label: '无需上传', value: '2' },
])
// 跳过物流
const skipList = ref([
    { label: '是', value: '1' },
    { label: '否', value: '0' },
])
// 部门类型
const departmentTypeList = ref()
/** 
 * 获取部门类型
 */
const getdeptType = async () => {
    const res = await getSystemList({ parentId: '1861962988832542721' })
    const data = res.data.filter((item: any) => item.deptName.includes('招商'))
    departmentTypeList.value = data
}
/** 商品状态流转 */
const handleChangeStatus = async (row: any, statusName: string) => {
    switch (statusName) {
        case '上架':
            await editFive(Qs.stringify({ ids: [row.id] }, { arrayFormat: 'repeat' }));
            proxy?.$modal.msgSuccess('商品上架成功');
            await getList()
            break;
        case '退还':
            ElMessageBox.confirm('确认将选中商品退还供应商？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                callback: async (action: Action) => {
                    if (action == 'confirm') {
                        await outSupplier({ id: row.id })
                        proxy?.$modal.msgSuccess('商品退还成功');
                        await getList()
                    }
                },
            })
            break;
        default:
            break;
    }
}
// 查询列表数据
const getList = async () => {
    try {
        loading.value = true
        // const params = { ...queryParams.value, productStatus: 2, recruiterDeptId: queryParams.value.recruiterDeptIds || queryParams.value.recruiterDeptId }
        const { rows = [], total = 0 } = await hmRankinglist(queryParams.value)
        tableData.value = rows
        tableTotal.value = total
        loading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
// 获取选品部门
const getAnchor = async () => {
    const res = await getAnchorList({ deptId: "1782395835898970113" })
    anchorList.value = res.rows
}
/** 重置按钮操作 */
const resetQuery = () => {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        deptId: '',
        userName: '',
        stageName: '',
        startTime: '',
        endTime: '',
    }
    handleClear();
    handleQuery();
};
/** 完成时间筛选 */
const pickerChange = (val: string[]) => {
    if (val) {
        queryParams.value.startTime = val[0];
        queryParams.value.endTime = val[1];
    } else {
        queryParams.value.startTime = '';
        queryParams.value.endTime = '';
    }
};
// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {
}


/**
 * 部门筛选
 */
const departmentTypeChange = async (parentId: string) => {
    // if (parentId) {
    //     // queryParams.value.recruiterDeptIds = ''
    //     queryParams.value.deptId = ''
    //     const res = await getSystemList({ parentId })
    //     deptList.value = res.data
    //     recruiterList.value = []
    // } else {
    //     deptList.value = []
    //     recruiterList.value = []
    //     // queryParams.value.recruiterDeptIds = ''
    //     queryParams.value.deptId = ''
    // }
}
// 根据招商部获取招商员
const deptChange = async (event: string) => {
    // if (event) {
    //     const res = await getUserList({ deptId: event })
    //     recruiterList.value = res.rows
    //     queryParams.value.recruiterUserId = ''
    // } else {
    //     recruiterList.value = []
    //     queryParams.value.recruiterUserId = ''
    // }
    // queryParams.value.recruiterUserId = ''
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
    ids.value = selection.map((item: any) => item.id);
    selectedStatus.value = selection.map((item: any) => item.auditStatus);
};
const router = useRouter();
/** 跳转排行榜 */
const handleOperate = () => {

    // router.push("/listBoardindex");
    const targetRoute = router.resolve({ name: 'listBoardindex' });
    window.open(targetRoute.href, '_blank');
}
// 直播机制反显
const computedMechanism = (row: any, numbers: string) => {
    if (row) {
        const price = row.price ? row.price : '-'
        const commission = row.commission ? row.commission + '%' : '-'
        const brokerage = row.brokerage ? row.brokerage + '%' : '-'
        const liveStreamingMechanism = row.liveStreamingMechanism ? row.liveStreamingMechanism : '-'
        const costPrice = row.costPrice ? row.costPrice : '-'
        if (row.cooperationMode) {
            if (row.cooperationMode == '分佣') {
                return '机制' + numbers + ': ' + '售价:' + price + ' 佣金:' + commission + ' 补充佣金:' + brokerage + ' 机制:' + liveStreamingMechanism + ' 成本:' + costPrice
            } else {
                return '机制' + numbers + ': ' + '成本:' + costPrice + ' 机制:' + liveStreamingMechanism
            }
        }
    }
}

/** 查看商品详情 */
const handleInfo = (row: any, title: string) => {
    isAddDrawer.value = true;
    AddFormTitle.value = title
    AddFormId.value = row.id
    AddFormlist.value = row;
};
const AddFormlist = ref([])
// 弹框关闭
const handleClose = async () => {
    if (AddFormTitle.value == '查看详情') {
        isAddDrawer.value = false
    } else {
        await proxy?.$modal.confirm('是否退出当前编辑页面，已编辑的商品信息将被清空');
        isAddDrawer.value = false
    }
}
// 商品提交回调函数
const AddFormSubmit = () => {
    isAddDrawer.value = false
    getList()
}
/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('排行榜数据管理')
    commodityManage.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
onMounted(async () => {
    await getColmun()
    await getList()
    getdeptType()
    getCategoryList()
    getDeptLists()
    getAnchor();
})
// 查询类目
const getCategoryList = async () => {
    const { data = [] } = await categoryList({})
    categoryProps.value = removeInvalidNodes(data, 'categoryStatus');
}

// 获取供应商列表
const getHmSupplierList = async () => {
    supplierLoading.value = true
    const res = await loginSupplierByRoleList(supplierNameDate.value)
    const reshandle = res.rows.map((item: any) => (
        {
            label: item.supplierName,
            value: item.supplierName
        }
    ))
    supplierNameOptions.value.push(...reshandle)
    supplierNametotal.value = res.total
    supplierLoading.value = false
}
/** select懒加载 */
const selectLoad = async () => {
    if (supplierNameOptions.value.length < supplierNametotal.value) {
        supplierNameDate.value.pageNum++;
        getHmSupplierList()
    }
}
/** 远程搜索 */
const searchQuery = async (query: string) => {
    supplierQueryLoading.value = true
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    supplierNameDate.value.supplierName = query
    await getHmSupplierList()
    supplierQueryLoading.value = false
}
/** 清空供应商 */
const handleClear = () => {
    supplierNameDate.value.supplierName = ''
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    getHmSupplierList()
}
// 获取招商部
const getDeptLists = async () => {
    const res = await loginDeptList()
    deptList.value = res.data
}
</script>

<style lang="scss" scoped>
.circular {
    display: inline;
    height: 30px;
    width: 30px;
    animation: loading-rotate 2s linear infinite;
}

.path {
    animation: loading-dash 1.5s ease-in-out infinite;
    stroke-dasharray: 90, 150;
    stroke-dashoffset: 0;
    stroke-width: 2;
    stroke: var(--el-color-primary);
    stroke-linecap: round;
}

.supplierSelect {
    :deep(.el-popper) {
        left: 0 !important;
        top: 34px !important;
        z-index: 7000 !important;
        width: 100% !important;
    }
}

.visaExemption {
    width: 14px;
}

.supplierName_text {
    overflow: hidden;
    overflow-wrap: break-word;
    text-overflow: ellipsis;
    line-height: 1;
}

.supplierName {
    display: flex;
    align-items: center;
    justify-content: center;

    .el-image {
        width: 16px;
        height: 16px;
    }

}

.supplierSelect_icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.el-select-loading__tips {
    color: #606266;
    font-size: 14px;
}

:deep(.el-tabs__content) {
    overflow: visible !important;
}

.flex {
    display: flex;
    align-items: center;
    justify-content: center;
}

.el-select-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: initial;
    pointer-events: none;
    color: var(--el-color-info);
    font-size: 12px;

    &__icon {
        font-size: 16px;
        animation: rotate 1.5s linear infinite;
    }

    &__tips {
        margin-left: 6px;
    }

    @keyframes rotate {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }
}
</style>